package cstruct

import (
	"fmt"
	"reflect"
)

// struct to map
// 如果定义了tag 则以tag定义的key为主键 mk > from > json
func StructToMap(obj interface{}) map[string]interface{} {
	t := reflect.TypeOf(obj)
	v := reflect.ValueOf(obj)

	var data = make(map[string]interface{})
	for i := 0; i < t.NumField(); i++ {
		tt, _ := t.FieldByName(t.Field(i).Name)

		mk, err := GetKeyNameFromTag(tt.Tag)
		if err != nil {
			data[string(t.Field(i).Name)] = v.Field(i).Interface()
		} else {
			data[mk] = v.Field(i).Interface()
		}
	}
	return data
}

// 通过tag获取key名称
func GetKeyNameFromTag(tag reflect.StructTag) (string, error) {
	if v, ok := tag.Lookup("mk"); ok {
		return v, nil
	}

	if vf, ok := tag.Lookup("form"); ok {
		return vf, nil
	}

	if vj, ok := tag.Lookup("json"); ok {
		return vj, nil
	}

	return "", fmt.Errorf("未找到key定义")
}
